<!-- 隐患汇总 -->
<template>
	<view class="resgistration-container">

		<uni-forms ref="hiddenForm" :rules="rules" :modelValue="hiddenForm" border>
			<uni-forms-item label="检查负责人：" name="examineExecutorName">
				<uni-easyinput v-model="hiddenForm.examineExecutorName" disabled placeholder="请输入"
					:inputBorder="false" />
			</uni-forms-item>
			<uni-forms-item label="检查时间：" required name="taskTime">
				<uni-easyinput v-model="hiddenForm.taskTime" placeholder="请输入" disabled :inputBorder="false" />
			</uni-forms-item>

			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="计划上报时间：" required name="plannedReportingTime">
				<uni-datetime-picker type="date" :clear-icon="false" disabled
					v-model="hiddenForm.plannedReportingTime" />
			</uni-forms-item>

			<!-- 	<uni-forms-item label="上传检查图片：" required name="hiddenDangerDeptName">

			</uni-forms-item> -->

		</uni-forms>

		<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
			@selection-change="selectionChange">
			<uni-tr>
				<uni-th align="center">序号</uni-th>
				<uni-th align="center">隐患名称</uni-th>
				<uni-th align="center">隐患描述</uni-th>
				<uni-th align="center">隐患等级</uni-th>
				<uni-th align="center">是否现场解决</uni-th>
				<uni-th align="center">提交人</uni-th>
				<uni-th align="center">提交时间</uni-th>
			</uni-tr>
			<uni-tr v-for="(item, index) in hiddenData" :key="index">
				<uni-td>{{ index +1 }}</uni-td>
				<uni-td>
					<view class="name" align="center">{{ item.hiddenDangerName }}</view>
				</uni-td>
				<uni-td align="center">{{ item.hiddenDangerDescription }}</uni-td>
				<uni-td align="center">{{ formatDangerLevel(item.hiddenDangerLevel) }}</uni-td>
				<uni-td align="center">{{ formatSolution(item.isSiteSolution) }}</uni-td>
				<uni-td align="center">{{item.createBy}}</uni-td>
				<uni-td align="center">{{item.createTime}}</uni-td>

			</uni-tr>
		</uni-table>
		<uni-forms ref="examineForm" class="examin-form" :rules="examineRules" :modelValue="examineForm" border>
			<uni-forms-item label="审批操作：" name="approveStatus">
				<uni-data-checkbox v-model="examineForm.approveStatus"
					:localdata="approveStatusOption"></uni-data-checkbox>
			</uni-forms-item>
			<template v-if="examineForm.approveStatus == 1">
				<view class="title"> 负责人签字 </view>
				<view class="charge-people">

					<view class="sign" v-if="signObj.url == ''"
						@click="handleSign()"> 请在这个区域进行签字
					</view>
					<view v-if="signObj.url" class="view-img">
						<image :src="signObj.url"></image>
					</view>
					<!-- <view class="time">月 日 时 分</view> -->
				</view>
				<uni-forms-item label="审批意见：" name="approveRemark">
					<uni-easyinput type="textarea" v-model="examineForm.approveRemark" focus
						placeholder="请输入内容"></uni-easyinput>
				</uni-forms-item>
			</template>
			<template v-if="examineForm.approveStatus == 2">
				<uni-forms-item label="审批意见：" name="approveRemark">
					<uni-easyinput type="textarea" v-model="examineForm.approveRemark" focus
						placeholder="请输入内容"></uni-easyinput>
				</uni-forms-item>
			</template>
		</uni-forms>

		<view class="btn">
			<button type="default" class="mini-btn" size="mini" @click="cancel"> 取消 </button>
			<button type="primary" class="mini-btn" size="mini" @click="onSubmit"> 确认 </button>
		</view>
		<!-- 签字弹窗 -->
		<uni-popup ref="popup" type="center" width="100%" background-color="#fff" height="600px">
			<uni-nav-bar back-text="返回" title="签字"></uni-nav-bar>

			<view style="width: 750rpx ;height: 500rpx;">
				<jp-signature ref="signatureRef"></jp-signature>
			</view>
			<view>
				<button @click="clear">清空</button>
				<button @click="undo">撤消</button>
				<button @click="save">保存</button>
			</view>
			</u-form>
		</uni-popup>
	</view>

</template>

<script>
	import {
		mapGetters
	} from "vuex"

	import {
		sendRegular,
		detailRegister,
		detailViewRegister
	} from "@/api/hiddenTrouble/periodShoot.js";
	import {
		deptTreeSelect
	} from "@/api/system/user";
	export default {
		onLoad(e) {
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('acceptDataFromOpenedPage', (data) => {
				this.checkId = data.checkId
				this.detailObj = data.totalObj
				this.handleOpen(this.detailObj.summaryFour)
			})
		},

		data() {
			return {
				checkFileList: [],
				fileList: [],
				//选中ID
				checkId: null,
				//加载中
				loading: false,
				//审核负责人签字
				signObj:{
					url: ''
				},
				//审核的form
				examineForm: {
					url: '',
					fileInfoList: []
				},
				//隐患登记表
				hiddenData: [],
				//人员填报表
				userFillData: [],
				//审批的option
				approveStatusOption: [{
						text: "通过",
						value: 1
					},
					{
						text: "驳回",
						value: 2
					},
				],
				//详情
				detailObj: {},
				//审批校验规则
				examineRules: {},
				//校验规则
				rules: {},
				//部门数据
				treeData: [],
				//隐患登记
				hiddenForm: {
					isSiteSolution: 2,
				},
				hiddenLevelOption: [{
						text: '一般隐患',
						value: 1
					},
					{
						text: '重大隐患',
						value: 2
					},

				],
				solveOption: [{
						text: '是',
						value: 1
					},
					{
						text: '否',
						value: 2
					},
				],
			}
		},
		methods: {

			//格式化隐患等级
			formatDangerLevel(val) {
				switch (val) {
					case 1:
						return "一般隐患";
					case 2:
						return "重大隐患";
					default:
						break;
				}
			},
			//格式化是否现场解决
			formatSolution(val) {
				switch (val) {
					case 1:
						return "是";
					case 2:
						return "否";
					default:
						break;
				}
			},
			//保存
			save() {
				let config = require('@/config.js')
				// 是否为空画板 无签名

				this.$refs.signatureRef.canvasToTempFilePath({
					success: (res) => {
						// 生成图片的临时路径
						// H5 生成的是base64
						if (res.isEmpty == false) {
							// this.url = res.tempFilePath
							let blob = this.dataURLtoBlob(res.tempFilePath);
							// 拿到文件名
							let fileName = "电子签名.jpg";
							// 2，在转为 file类型
							let file = this.blobToFile(blob, fileName);
							const formData = new FormData();
							formData.append("file", file);

							uni.uploadFile({
								url: `${config.baseUrl}/common/upload`,
								header: {
									'Authorization': 'Bearer ' + uni.getStorageSync(
										'App-Token') //请求头信息
								},
								filePath: res.tempFilePath,
								name: 'file',
								success: (res) => {
									let response = JSON.parse(res.data)
									response.type = "56" //我制定的审批步骤
									response.fileId = response.id
									delete response.code
									delete response.msg
									delete response.systemTime
									delete response.originalFilename
									console.log("response", response)
									this.signObj = response
									this.examineForm.fileInfoList.push(response)
									// let res = await sendRegular(query);
									// @params  status: 状态判断上传文件穿什么type
									this.$refs.popup.close()

								}
							})
						}
					}
				})
			},

			//1,先将base64转换为blob
			dataURLtoBlob(baseurl) {
				var arr = baseurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			//2,再将blob转换为file
			blobToFile(theBlob, fileName) {
				theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
				theBlob.name = fileName; // 文件名
				return new File([theBlob], fileName, {
					type: theBlob.type,
					lastModified: Date.now(),
				});
			},
			//清除
			clear() {
				this.$refs.signatureRef.clear()
			},
			//撤销按钮
			undo() {
				this.$refs.signatureRef.undo()
			},
			//签字的按钮
			handleSign(val) {


				this.$refs.popup.open('center')
			},
			//删除隐患登记表数据
			handleDelete(row) {
				this.hiddenData.map((item, index) => {
					if (item.id == row.id) {
						this.hiddenData.splice(index, 1);
					}
				});
			},
			//修改
			handleEdit(row) {},
			//取消按钮
			cancel() {
				uni.navigateBack({
					delta: 1, //返回层数，2则上上页
				})
			},
			/** 提交按钮 */
			onSubmit() {
				this.$refs.hiddenForm.validate().then(async (res) => {
					// console.log('表单数据信息：', res);

					let query = {
						id: this.checkId,
						approveRemark: this.examineForm.approveRemark,
						approveStatus: this.examineForm.approveStatus,
						fileInfoList: this.examineForm.fileInfoList,
					};
					console.log("提交参数1", query, this.submitForm);
					let response = await sendRegular(query);

					uni.showToast({
						title: "审批成功"
					})
					uni.navigateTo({
						url: "/pages/trouble/index"
					})

				}).catch(err => {
					console.log('表单错误信息：', err);
				})


			},
			handleOpen(data) {
				console.log("data===", data)
				this.hiddenForm = data;
				this.fileList = data.fileInfoList;
				this.hiddenData = data.hiddentroubleInspectionRegisters;
				this.userFillData = data.personnelFillingForms;
				if (this.operateStatus == 0) {
					this.fileList = data.fileInfoList?.filter((item) => {
						return item.type == 25;
					});
					this.checkFileList = data.fileInfoList?.filter((item) => {
						return item.type == 24;
					});
				}
			},
			/** 被检查部门部门下拉树结构 */
			async getDeptTree() {
				const response = await deptTreeSelect();
				this.treeData = response.data;
			},
		},
		mounted() {

			// this.handleOpen()
			this.getDeptTree()


		},

		watch: {
			current: {
				async handler(val) {

					if (val == 0) {
						let query = {
							regularId: this.checkId,
						};
						let res = await detailViewRegister(query);
						this.hiddenData = res.rows;
					} else if (val == 1) {

						this.userFillData = this.detailObj.summaryThree.personnelFillingForms;
					}

				},
				immediate: true
			}
		},
		computed: {
			...mapGetters(["allUsers"]),

		}
	}
</script>

<style lang="scss" scoped>
	.resgistration-container {
		padding: 20rpx;
		background-color: #fff;
		overflow-y: auto;
		height: 100vh;

		.btn {
			text-align: right;
			margin-top: 5px;

			.mini-btn {
				margin-right: 10px !important;
			}
		}

		.examin-form {
			.title {
				margin: 20rpx 0;
				height: 60rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 32rpx;
				color: #515a6e;
				text-align: left;
				font-style: normal;
			}

			// 动火负责人签字
			.charge-people {
				position: relative;
				padding: 20rpx;
				background: #ffffff;
				border-radius: 20rpx;
				border: 2rpx solid #dcdee2;

				.check-box {
					margin-right: 20rpx;
				}

				.sign {
					margin-top: 20rpx;
					height: 240rpx;
					background: #ffffff;
					border-radius: 10rpx;
					border: 2rpx dashed #dcdee2;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 32rpx;
					color: #c5c8ce;
					line-height: 200rpx;
					text-align: center;
					font-style: normal;
				}
				.view-img{
					    border: 1px dashed #e8e0e0;
				}

				.time {
					position: absolute;
					bottom: 20rpx;
					right: 5%;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					color: #808695;
					font-style: normal;
				}
			}
		}

		::v-deep {
			.uni-forms-item--border {
				border-top: 0 solid #000;
				border-bottom: 2rpx solid #e8eaec;
			}

			.uni-forms-item__label {
				width: 40% !important;
			}

			.submit-btn {
				margin-top: 30rpx;
				background: #137ee9;
				border-radius: 10rpx;
			}
		}
	}
</style>